/**
 * 160. 相交链表
 * https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
 */
const { createListNode, getListNodeTail } = require('../../libs/public');

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
function getIntersectionNode(headA, headB) {
  let nodeA = headA;
  let nodeB = headB;
  while (nodeA && nodeB) {
    if (nodeA === nodeB) {
      return nodeA;
    }
    nodeA = nodeA.next;
    nodeB = nodeB.next;
  }
  if (!nodeA && !nodeB) {
    return null;
  }
  let longer;
  let shorter;
  let nodeL;
  let nodeS;
  if (!nodeA) {
    longer = headB;
    shorter = headA;
    nodeL = longer;
    nodeS = shorter;
    while (nodeB) {
      nodeL = nodeL.next;
      nodeB = nodeB.next;
    }
  } else {
    longer = headA;
    shorter = headB;
    nodeL = longer;
    nodeS = shorter;
    while (nodeA) {
      nodeL = nodeL.next;
      nodeA = nodeA.next;
    }
  }
  while (nodeL && nodeS) {
    if (nodeL === nodeS) {
      return nodeL;
    }
    nodeL = nodeL.next;
    nodeS = nodeS.next;
  }
  return null;
}

let headA;
let headB;
let headC;

headA = createListNode([4, 1]);
headB = createListNode([5, 6, 1]);
headC = createListNode([8, 4, 5]);
getListNodeTail(headA).next = headC;
getListNodeTail(headB).next = headC;
console.log(getIntersectionNode(headA, headB).val === 8);

headA = createListNode([1, 9, 1]);
headB = createListNode([3]);
headC = createListNode([2, 4]);
getListNodeTail(headA).next = headC;
getListNodeTail(headB).next = headC;
console.log(getIntersectionNode(headA, headB).val === 2);

headA = createListNode([2, 6, 4]);
headB = createListNode([1, 5]);
console.log(getIntersectionNode(headA, headB) === null);
